/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-05-09
 * Time: 14:35
 */


class Solution {
    public int[] searchRange(int[] nums, int target) {
        //寻找第一个target
        int start = findBeginTarget(nums,target);
        //寻找最后一个target
        int end = findEndTarget(nums,target);
        return new int[]{start,end};
    }
    private int findBeginTarget(int[] nums, int target){
        int left =0;
        int right = nums.length-1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(nums[mid]==target){
                if(mid==0||nums[mid-1]<target){
                    return mid;
                }
                right = mid-1;
            }else if(nums[mid]>target){
                right = mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }

    private int findEndTarget(int[] nums, int target){
        int left =0;
        int right = nums.length-1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(nums[mid]==target){
                if(mid==nums.length-1||nums[mid+1]>target){
                    return mid;
                }
                left = mid+1;
            }else if(nums[mid]>target){
                right = mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }
}


class Solution1 {
    public int search(int[] nums, int target) {
        //寻找第一个target
        int start = findBeginTarget(nums,target);
        //寻找最后一个target
        int end = findEndTarget(nums,target);
        if(start==-1&&end==-1){
            return 0;
        }
        else if(start==-1||end==-1){
            return 1;
        }else {
            return (end-start+1);
        }
    }

    private int findBeginTarget(int[] nums, int target){
        int left =0;
        int right = nums.length-1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(nums[mid]==target){
                if(mid==0||nums[mid-1]<target){
                    return mid;
                }
                right = mid-1;
            }else if(nums[mid]>target){
                right = mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }

    private int findEndTarget(int[] nums, int target){
        int left =0;
        int right = nums.length-1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(nums[mid]==target){
                if(mid==nums.length-1||nums[mid+1]>target){
                    return mid;
                }
                left = mid+1;
            }else if(nums[mid]>target){
                right = mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }
}
public class TestLeetCode {

    public static void main(String[] args) {

    }

}
